package com.gzlg.hospital.controller;

import com.gzlg.hospital.pojo.*;
import com.gzlg.hospital.service.AdminService;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    // 医生管理
    @GetMapping("/doctor/list")
    public String listDoctors(Model model) {
        List<Doctor> doctors = adminService.findAllDoctors();
        doctors.forEach(doctor -> {
        });
        model.addAttribute("doctors", doctors);
        return "Admin/doctor_list";
    }

    @GetMapping("/doctor/add")
    public String showDoctorForm(Model model) {
        model.addAttribute("doctor", new Doctor());
        return "Admin/doctor_form";
    }

    @PostMapping("/doctor/save")
    public String saveDoctor(@ModelAttribute Doctor doctor, RedirectAttributes redirectAttributes) {
        if (doctor.getId() == null) {
            adminService.saveDoctor(doctor);
            redirectAttributes.addFlashAttribute("message", "医生添加成功");
        } else {
            adminService.updateDoctor(doctor);
            redirectAttributes.addFlashAttribute("message", "医生信息更新成功");
        }
        return "redirect:/admin/doctor/list";
    }

    @GetMapping("/doctor/edit/{id}")
    public String editDoctor(@PathVariable Integer id, Model model) {
        model.addAttribute("doctor", adminService.findDoctorById(id));
        return "Admin/doctor_form";
    }

    @GetMapping("/doctor/delete/{id}")
    public String deleteDoctor(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        adminService.deleteDoctorById(id);
        redirectAttributes.addFlashAttribute("message", "医生删除成功");
        return "redirect:/admin/doctor/list";
    }

    //患者用户管理
    // 显示患者列表

    @GetMapping("/patient/list")
    public String listPatients(Model model) {
        List<Patient> patients = adminService.findAllPatients();
        model.addAttribute("patients", patients);
        return "Admin/patient_list";
    }

    // 显示添加表单
    @GetMapping("/patient/add")
    public String showAddForm(Model model) {
        model.addAttribute("patient", new Patient());
        return "Admin/patient_form";
    }

    // 显示编辑表单
    @GetMapping("/edit/{id}")
    public String editPatient(@PathVariable Integer id, Model model) {
        model.addAttribute("patient", adminService.findPatientById(id));
        return "Admin/patient_form";
    }

    // 保存或更新患者
    @PostMapping("/patient/save")
    public String savePatient(@ModelAttribute Patient patient) {
        if (patient.getRole() == null || patient.getRole().isEmpty()) {
            patient.setRole("patient");
        }
        if (patient.getId() == null) {
            adminService.savePatient(patient);
        } else {
            adminService.updatePatient(patient);
        }
        return "redirect:/admin/patient/list";
    }

    // 删除患者
    @GetMapping("/delete/{id}")
    public String deletePatient(@PathVariable Integer id) {
        adminService.deletePatientById(id);
        return "redirect:/admin/patient/list";
    }

    //根据患者id查询患者的挂号记录
    @GetMapping("/registration/list")
    public String searchRegistrationsByPatient_id(
            @RequestParam(name = "patient_id", required = false) Integer patient_id,
            Model model) {

        logger.info("searchRegistrationsByPatient_id method called with patient_id: {}", patient_id);

        if (patient_id != null && patient_id > 0) {
            List<Registration> registrations = adminService.getRegistrationsByPatient_id(patient_id);
            logger.info("Found {} registrations for patient_id: {}", registrations.size(), patient_id);
            model.addAttribute("registrations", registrations);
            model.addAttribute("patient_id", patient_id);
        } else {
            logger.info("No valid patient_id provided.");
        }

        return "Admin/registration_list";
    }







    // 药品管理
    @GetMapping("/drug/list")
    public String listDrugs(Model model) {
        model.addAttribute("drugs", adminService.findAllPharmaceuticals());
        return "Admin/drug_list";
    }

    @GetMapping("/drug/add")
    public String showDrugForm(Model model) {
        model.addAttribute("drug", new Pharmaceutical());
        return "Admin/drug_form";
    }

    @PostMapping("/drug/save")
    public String saveDrug(@ModelAttribute("drug") Pharmaceutical drug, RedirectAttributes redirectAttributes) {
        if (drug.getId() == null) {
            adminService.savePharmaceutical(drug);
            redirectAttributes.addFlashAttribute("message", "药品添加成功");
        } else {
            adminService.updatePharmaceutical(drug);
            redirectAttributes.addFlashAttribute("message", "药品信息更新成功");
        }
        return "redirect:/admin/drug/list";
    }

    @GetMapping("/drug/edit/{id}")
    public String editDrug(@PathVariable Integer id, Model model) {
        model.addAttribute("drug", adminService.findPharmaceuticalById(id));
        return "Admin/drug_form";
    }

    @GetMapping("/drug/delete/{id}")
    public String deleteDrug(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        adminService.deletePharmaceuticalById(id);
        redirectAttributes.addFlashAttribute("message", "药品删除成功");
        return "redirect:/admin/drug/list";
    }



    // 检查项目管理页面
    @GetMapping("/checkItems")
    public String listCheckItems(Model model) {
        model.addAttribute("checkItems", adminService.findAllCheckItems());
        return "Admin/checkitem_list";
    }

    // 新增检查项目页面
    @GetMapping("/checkItem/add")
    public String showCheckItemForm(Model model) {
        model.addAttribute("checkItem", new CheckItem());
        return "Admin/checkitem_form";
    }

    // 保存检查项目
    @PostMapping("/checkItem/save")
    public String saveCheckItem(@ModelAttribute CheckItem checkItem, RedirectAttributes redirectAttributes) {
        if (checkItem.getId() == null) {
            adminService.saveCheckItem(checkItem);
            redirectAttributes.addFlashAttribute("message", "检查项目添加成功");
        } else {
            adminService.updateCheckItem(checkItem);
            redirectAttributes.addFlashAttribute("message", "检查项目更新成功");
        }
        return "redirect:/admin/checkItems";
    }

    // 编辑检查项目
    @GetMapping("/checkItem/edit/{id}")
    public String editCheckItem(@PathVariable Integer id, Model model) {
        model.addAttribute("checkItem", adminService.findCheckItemById(id));
        return "Admin/checkitem_form";
    }

    // 删除检查项目
    @GetMapping("/checkItem/delete/{id}")
    public String deleteCheckItem(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        adminService.deleteCheckItemById(id);
        redirectAttributes.addFlashAttribute("message", "检查项目删除成功");
        return "redirect:/admin/checkItems";
    }



    // 排班管理
    @GetMapping("/schedule/add")
    public String showAddScheduleForm(@RequestParam(value = "doctor_id", required = false) Integer doctor_id, @RequestParam(value = "doctor_name", required = false) String doctor_name, Model model) {
        Schedule schedule = new Schedule();
        List<String> departments = adminService.getAllDepartments();
        model.addAttribute("departments", departments);
        // 验证参数一致性：如果其中一个参数存在，另一个也必须存在
        if ((doctor_id != null && doctor_name == null) || (doctor_id == null && doctor_name != null)) {
            logger.info("Received doctor_id: {}, doctor_name: {}", doctor_id, doctor_name);

        } else if (doctor_id != null) {
            schedule.setDoctor_id(doctor_id);
            schedule.setDoctor_name(doctor_name);
        }
        model.addAttribute("schedule", schedule);
        model.addAttribute("doctors", adminService.findAllDoctors());
        return "Admin/schedule_add";
    }

    @GetMapping("/schedule/list")
    public String listSchedules(Model model) {
        model.addAttribute("schedules", adminService.findAllSchedules());
        model.addAttribute("doctors", adminService.findAllDoctors());
        model.addAttribute("schedule", new Schedule());
        return "Admin/schedule_list";
    }

    @PostMapping("/schedule/save")
    public String saveSchedule(@ModelAttribute Schedule schedule, RedirectAttributes redirectAttributes) {
        if (schedule.getDoctor_id() == null) {
            logger.info("Received schedule: {}", schedule);
            redirectAttributes.addFlashAttribute("error", "医生ID不能为空");
            return "redirect:/admin/schedule/add";
        }
        adminService.saveSchedule(schedule);
        return "redirect:/admin/schedule/list";
    }

    @GetMapping("/schedule/delete/{id}")
    public String deleteSchedule(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        adminService.deleteScheduleById(id);
        redirectAttributes.addFlashAttribute("message", "排班删除成功");
        return "redirect:/admin/schedule/list";
    }
    @GetMapping("/schedule/edit/{id}")
    public String showEditScheduleForm(@PathVariable("id") Integer id, Model model) {
        Schedule schedule = adminService.findScheduleById(id);
        if (schedule == null) {
            return "error";
        }
        model.addAttribute("schedule", schedule);
        return "Admin/schedule_edit";
    }
    @PostMapping("/schedule/edit/{id}")
    public String updateSchedule(@PathVariable("id") Integer id, @ModelAttribute("schedule") Schedule schedule, RedirectAttributes redirectAttributes) {
        // 确保主键正确设置
        schedule.setId(id);
        // 调用更新方法
        adminService.update(schedule);
        redirectAttributes.addFlashAttribute("message", "排班信息更新成功");
        return "redirect:/admin/schedule/list";
    }


    //床位管理
    // 显示病床列表
    @GetMapping("/bed/list")
    public String listBeds(Model model) {
        List<Bed> beds = adminService.findAllBeds();
        model.addAttribute("beds", beds);
        return "Admin/bed_list";
    }

    // 显示添加表单
    @GetMapping("/bed/add")
    public String showAddBedForm(Model model) {
        model.addAttribute("bed", new Bed());
        return "Admin/bed_form";
    }

    // 显示编辑表单
    @GetMapping("/bed/edit/{id}")
    public String editBed(@PathVariable Integer id, Model model) {
        model.addAttribute("bed", adminService.findBedById(id));
        return "Admin/bed_form";
    }

    // 保存或更新病床
    @PostMapping("/bed/save")
    public String saveBed(@ModelAttribute Bed bed) {
        if (bed.getId() == null) {
            adminService.saveBed(bed);
        } else {
            adminService.updateBed(bed);
        }
        return "redirect:/admin/bed/list";
    }

    // 删除病床
    @PostMapping("/bed/delete/{id}")
    public String deleteBed(@PathVariable Integer id) {
        adminService.deleteBedById(id);
        return "redirect:/admin/bed/list";
    }



    // 登录与主页
    @GetMapping("/login")
    public String showLoginForm(Model model) {
        model.addAttribute("admin", new Admin());
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String account, @RequestParam String pwd,
                        RedirectAttributes redirectAttributes, HttpSession session) {
        Admin admin = adminService.adminlogin(account);
        if (admin != null) {
            session.setAttribute("admin", admin);
            return "redirect:/admin/index";
        } else {
            redirectAttributes.addFlashAttribute("message", "登录失败");
            return "redirect:/admin/login";
        }
    }

    @GetMapping("/index")
    public String adminIndex() {
        return "Admin/AdminIndex";
    }
}
